package com.hwd.srb.core.hfb;

import com.alibaba.fastjson.JSONObject;
import com.hwd.srb.common.util.MD5;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Slf4j
public class RequestHelper {

    public static void main(String[] args) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("d", "4");
        paramMap.put("b", "2");
        paramMap.put("c", "3");
        paramMap.put("a", "1");

        paramMap.remove("sign");
    }

    /**
     * 请求数据获取签名
     *
     * @param paramMap 请求数据
     * @return String
     */
    public static String getSign(Map<String, Object> paramMap) {
        paramMap.remove("sign");

        TreeMap<String, Object> sorted = new TreeMap<>(paramMap);
        StringBuilder str = new StringBuilder();

        sorted.forEach((key, value) -> str.append(value).append("|"));
        str.append(com.hwd.srb.core.hfb.HfbConst.SIGN_KEY);

        log.info("加密前：" + str.toString());

        String md5Str = MD5.encrypt(str.toString());

        log.info("加密后：" + md5Str);

        return md5Str;
    }

    /**
     * Map转换
     *
     * @param paramMap 请求数据
     * @return Map<String, Object>
     */
    public static Map<String, Object> switchMap(Map<String, String[]> paramMap) {
        return paramMap.entrySet().stream().
                collect(Collectors.toMap(Map.Entry::getKey, param -> param.getValue()[0], (oldVal, newVal) -> newVal));
    }

    /**
     * 签名校验
     *
     * @param paramMap 请求数据
     * @return boolean
     */
    public static boolean isSignEquals(Map<String, Object> paramMap) {
        String sign = (String) paramMap.get("sign");
        String md5Str = getSign(paramMap);
        return sign.equals(md5Str);
    }

    /**
     * 获取时间戳
     *
     * @return long
     */
    public static long getTimestamp() {
        return new Date().getTime();
    }

    /**
     * 封装同步请求
     *
     * @param paramMap 请求数据
     * @param url      url
     * @return JSONObject
     */
    public static JSONObject sendRequest(Map<String, Object> paramMap, String url) {

        String result = "";

        try {
            //封装post参数
            StringBuilder postData = new StringBuilder();

            paramMap.forEach((key, value) -> postData
                    .append(key).append("=").append(value).append("&"));

            log.info(String.format("--> 发送请求到汇付宝：post data %1s", postData));

            byte[] reqData = postData.toString().getBytes("utf-8");
            byte[] respData = com.hwd.srb.common.util.HttpUtils.doPost(url, reqData);

            result = new String(respData);

            log.info(String.format("--> 汇付宝应答结果：result data %1s", result));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }
}
